package com.netease.xone.activity;

import msgCenter.MsgCenter;
import msgCenter.MsgManager;
import preferMgr.XonePrefHelper;
import protocol.XoneCallBack;
import protocol.XoneService;
import protocol.meta.LoopBack;
import Utils.StackTraceUtil;
import Utils.XoneUtil;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.KeyEvent;

import com.netease.framework.app.KillApplication;
import com.netease.log.NTLog;
import com.netease.mobidroid.DATracker;
import com.netease.pkgRelated.XoneConsts;
import com.netease.xone.R;
import com.netease.xone.app.XoneApp;
import com.netease.xone.fragment.FragmentMain;
import com.netease.xone.notification.NotificationBarMgr;
import com.netease.xone.widget.tabview.MainTab;

public class ActivityMain extends ActivityX1Base {
    private boolean mbBackKeyDown = false;
    private String TAG = ActivityMain.class.getSimpleName();
    

    public static void launch(Context context){
        Intent intent = new Intent(context, ActivityMain.class);
        //非activity的context启动activity会出错
        if(!(context instanceof Activity))
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        NTLog.d(TAG, StackTraceUtil.getMethodName() +
                " savedInstanceState=" + (null == savedInstanceState ? "null" : savedInstanceState.toString()));
        mActionBar.setDisplayHomeAsUpEnabled(false);
        
        /**
         * 使用replace方式，避免重复加入
         */
        if (null != findViewById(R.id.content_lay) && null == savedInstanceState) {
            /**
             * 恢复模式直接返回
             */
           
            FragmentManager fm = getSupportFragmentManager();
            FragmentTransaction ft = fm.beginTransaction();
            Fragment fragment = FragmentMain.newInstance(null);
            ft.replace(R.id.content_lay, fragment, null);
            ft.commit();
        }
        new Handler().postDelayed(mMyRunnable, 2000);
        Intent intent = getIntent();
        if(intent != null){
            redirectToPage(intent);
        }
        XoneService.getInstance().addListener(mXoneCallBack);
        MsgCenter.getInstance(getApplicationContext()).setAppExit(false);
    }
    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        NTLog.i(TAG, "onNewIntent");
       
    }
    private void redirectToPage(Intent intent) {
        int type = intent.getIntExtra(XoneConsts.BUNDLE_KEY.PUSH_TYPE, 0);
        if(type > 0){
            NTLog.i(TAG, "redirectToPage push type is " + type);
            switch(type){
                case XoneConsts.PUSHMSG_TYPE.Advice:
                    break;
                case XoneConsts.PUSHMSG_TYPE.PrivateMsg:
                    break;
                case XoneConsts.PUSHMSG_TYPE.AtMe:
                    break;
                case XoneConsts.PUSHMSG_TYPE.Comment:
                    break;
                case XoneConsts.PUSHMSG_TYPE.Praise:
                    break;
                case XoneConsts.PUSHMSG_TYPE.Dynamic:
                    break;
                case XoneConsts.PUSHMSG_TYPE.NewFans:
                    break;
            }
            MsgManager.deleteAllMsgByType(getApplicationContext(), type);
        }  
    }
    private Runnable mMyRunnable = new Runnable() {
        @Override
        public void run() {
//            if (XonePrefHelper.getNeedPush(getApplicationContext())) {
//                MsgCenter.getInstance(getApplicationContext()).launchService();
//            }
            String curVersion = XoneUtil.getNumberVersion(ActivityMain.this);
            if (curVersion.compareToIgnoreCase(XonePrefHelper
                    .getPreUpdateVersion(ActivityMain.this)) < 0) {
                MainTab.showMsg(MainTab.INDEX_OPTION);
            }
       } 
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        NTLog.d(TAG, StackTraceUtil.getMethodName());
        MsgCenter.getInstance(getApplicationContext()).setAppExit(true);
        XoneService.getInstance().removeListener(mXoneCallBack);
        DATracker.getInstance().upload();
    }
    
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
         if (keyCode == KeyEvent.KEYCODE_BACK) {
                mbBackKeyDown = true;
                return true;
        }
        mbBackKeyDown = false;
        return super.onKeyDown(keyCode, event);
    }
    
    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if(mbBackKeyDown){
                mbBackKeyDown = false;
                onExit();
                return true;
            }
        }
        mbBackKeyDown = false;
        return super.onKeyUp(keyCode, event);
    };

    public void onExit() {
        new AlertDialog.Builder(this).setTitle(R.string.tip).setMessage(R.string.exit_app)
                .setPositiveButton(R.string.sure, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialoginterface, int j) {
                        XoneService.getInstance().doLogout();
                        finish();
                        if (!XonePrefHelper.getNeedPush(getApplicationContext())) {
                            MsgCenter.getInstance(getApplicationContext()).stopService();
                        }
                        new Handler().postDelayed(new Runnable() {

                            @Override
                            public void run() {
                                KillApplication.killApplicationByPackageName(
                                        getApplicationContext(), getPackageName());
                            }
                        }, 1000);
                    }
                }).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface diagloginterface, int i) {
                    }
                }).show();
    }
    private XoneCallBack mXoneCallBack = new XoneCallBack() {

        @Override
        public void onLoopBack(int transactionId, Object obj) {
            if(obj != null && obj instanceof LoopBack){
                LoopBack lb = (LoopBack)obj;
                if(lb.mType == XoneConsts.LOOPBACK_TYPE.switch_account){
                    NTLog.i(TAG, "switch_account");
                    NotificationBarMgr.getInstance(getApplicationContext()).cancelPushAll();
                    if(lb.mData != null && lb.mData instanceof Boolean){
                        NTLog.i(TAG, "switch_account mData is " +lb.mData);
                    }
                    if (XonePrefHelper.getNeedPush(getApplicationContext())){
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                    NTLog.i(TAG, "reStartPush");
                                    MsgCenter.getInstance(getApplicationContext()).reStartPush();
                              
                            }
                        }, XoneApp.PUSH_DELAY_TIME);
                    }
                }
            }
        };
        
        @Override
        public void onAccException(int transactionId, int errCode, String err) {
            ActivityLogin.launch(ActivityMain.this, true, errCode);
        };
        
    };
}
    

